#include <algorithm>
#include "GUIManager.h"
#include "GUIObject.h"
#include "File.h"
#include "Factory.h"
#include "ReportError.h"
#include <GL/glut.h>

GUIManager::GUIManager()
{

}

void GUIManager::Draw()
{
	//MAKING EVERYTHING INTO 2D
	glEnable(GL_BLEND);
	glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
	glDisable(GL_DEPTH_TEST);
	glDepthMask(GL_FALSE);
	
	//setting Projection and ModelView Matrices to the identity
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();

	glDisable(GL_LIGHTING);

	GUIObjectVec::iterator it;

	//iterating through all the game objects and for any 
	//that are active, the draw function is called
	for (it = m_GUIObjVec.begin(); it != m_GUIObjVec.end(); ++it)
	{
		if ((*it)->IsActivated())
		{
			(*it)->Draw();
		}
	}

	//setting everything back to how it was
	glEnable(GL_LIGHTING);
	glEnable(GL_DEPTH_TEST);
	glDepthMask(GL_TRUE);
	glDisable(GL_BLEND);
}

void GUIManager::Update()
{
	//iterating through all the game objects and for any 
	//that are active, the update function is called
	for (m_it = m_GUIObjVec.begin(); m_it != m_GUIObjVec.end(); ++m_it)
	{
		if ((*m_it)->IsActivated())
		{
			(*m_it)->Update();
		}
	}
}

bool GUIManager::Load(const std::string& guiInfo)
{
	File f;
	if(!f.OpenRead(guiInfo))
	{
		ReportError("Can't find GUI info text file"); 
	}

	//Format is:
	//guiObj Type name
	// xy Pos
	// xy Size
	std::string typeName;
	if(!f.GetString(&typeName))
	{
		ReportError("Can't find guiObj typeName in guiInfo");
	}
	GUIObject* guiObj = TheGUIObjectFactory::Instance()->Create(typeName);
	
	float xPos,yPos;
	if(!f.GetFloat(&xPos))
	{
		ReportError("guiObj xPos not found in guiInfo");
	}
	if(!f.GetFloat(&yPos))
	{
		ReportError("guiObj yPos not found in guiInfo");
	}
	guiObj->SetPos(Vec2f(xPos,yPos));

	float xSize,ySize;
	if(!f.GetFloat(&xSize))
	{
		ReportError("guiObj xPos not found in guiInfo");
	}
	if(!f.GetFloat(&ySize))
	{
		ReportError("guiObj yPos not found in guiInfo");
	}
	guiObj->SetDims(Vec2f(xSize, ySize));


	return true;
}

void GUIManager::DeleteGUIObjects()
{
	for (m_it = m_GUIObjVec.begin(); m_it != m_GUIObjVec.end(); ++m_it)
	{
		delete (*m_it);
	}
	m_GUIObjVec.clear();
}

void GUIManager::AddGUIObject(GUIObject* GUIObj)
{
	m_GUIObjVec.push_back(GUIObj);
}

void GUIManager::RemoveGUIObject(GUIObject* GUIObj)
{
	//iterating through all the objects removing 
	//anything till it hits the end of the vector

	GUIObjectVec::iterator it = std::find(
		m_GUIObjVec.begin(), m_GUIObjVec.end(), GUIObj);

	if (it != m_GUIObjVec.end())
	{
		m_GUIObjVec.erase(it);
	}
}
